/************************************************************************

								Heroes IV
					  Copyright 2001, The 3DO Company

	------------------------------------------------------------------
  						    select_skill_from_set.cpp

	$Header: $

	$NoKeywords: $

 ************************************************************************/
// kill the 255+ character identifier warning.  Templates tend to exceed that easily.
#include "precompiled.h"
#pragma warning( disable: 4786 )

#include "select_skill_from_set.h"

#include "enum_operations.h"
#include "random.h"
#include "skill.h"
#include "skill_set.h"

//---------------------------------------------------------------
// Randomly select a skill from a list of available & required
// skills
//---------------------------------------------------------------
t_skill_type select_skill_from_set(t_skill_set const &available_skills, t_skill_set const &required_skills)
{
	t_skill_set const * skill_set;

	if (required_skills.any())
	{
		// Select from required skills
		skill_set = &required_skills;
	}
	else
	{
		// Select from available skills
		assert(available_skills.any());
		skill_set = &available_skills;
	}

	
	int index = random(0, skill_set->count() - 1);
	t_skill_type skill = t_skill_type(0);

	// Find first
	while (skill < k_skill_count && !skill_set->at(skill))
	{
		enum_incr(skill);
	}

	while (index)
	{
		enum_incr(skill);
		while (skill < k_skill_count && !skill_set->at(skill))
		{
			enum_incr(skill);
		}
		index--;
	}

	assert(skill < k_skill_count);

	return skill;
}
